package com.zidongxiangxi.rabbit.starter;

import com.zidongxiangxi.rabbit.starter.configuration.consumer.ReliableRabbitConsumerAutoConfiguration;
import com.zidongxiangxi.rabbit.starter.configuration.producer.ReliableRabbitProducerAutoConfiguration;
import com.zidongxiangxi.rabbit.starter.entity.ReliableRabbitProperties;
import com.zidongxiangxi.rabbit.starter.job.ZookeeperDaemonWorkThread;
import com.zidongxiangxi.rabbit.starter.manager.WorkThreadManager;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * reliable-rabbit自动配置
 *
 * @author chenxudong
 * @date 2020/11/08
 */
@Configuration
@AutoConfigureAfter({DataSourceAutoConfiguration.class, RabbitAutoConfiguration.class})
@ConditionalOnClass({JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({ReliableRabbitProperties.class})
@Import({ReliableRabbitProducerAutoConfiguration.class, ReliableRabbitConsumerAutoConfiguration.class})
public class ReliableRabbitAutoConfiguration {
	/**
	 * 定义jdbcTemplate
	 *
	 * @param dataSource 数据源
	 * @return jdbcTemplate
	 */
	@Bean
	@ConditionalOnMissingBean(JdbcTemplate.class)
	public JdbcTemplate jdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	/**
	 * 配置工作线程
	 *
	 * @param properties 可靠消息配置信息
	 * @return 工作线程管理类
	 */
	@Bean
	@ConditionalOnMissingBean(WorkThreadManager.class)
	public WorkThreadManager workThreadManager(
			ReliableRabbitProperties properties
	) {
		ZookeeperDaemonWorkThread daemonWorkThread = new ZookeeperDaemonWorkThread(properties.getApplication(),
				properties.getZookeeperAddress());
		return new WorkThreadManager(daemonWorkThread);
	}

}
